<?php
class GoodsModel extends Model {
    public function __construct() {
        parent::__construct();
        $this->tables = array(DB_FREFIX.'goods');
        $this->fields = array('id','nav','attr','brand','name','sn','price_sale','price_market','keyword','price_cost','unit','weight','thumbnail','content','is_up','is_freight','inventory','warn_inventory','date','service');
        $this->check  = new GoodsCheck();
        list(
                $this->R['id'],
                $this->R['aid'],
                $this->R['sn'],
                $this->R['navid'],
                $this->R['goodsid']
        ) = $this->getRequest()->getParams(
            array(
                isset($_GET['id']) ? $_GET['id'] : null,
                isset($_POST['aid']) ? $_POST['aid'] : null,
                isset($_POST['sn']) ? $_POST['sn'] : null,
                isset($_GET['navid']) ? $_GET['navid'] : null,
                isset($_GET['goodsid']) ? $_GET['goodsid'] : null
            )
        );
    }

    public function findAll() {
        $this->tables = array(DB_FREFIX.'goods as g',DB_FREFIX.'nav as n');
        $allGoods = parent::select($this->tables,array('g.id','g.brand','g.name','g.sn','g.price_sale','g.is_up','g.inventory','n.name as nav_name'),array('where'=>array('g.nav=n.id'),'limit'=>$this->limit,'order'=>'date DESC'));
        $allBrand = Tool::setObjectArray(parent::select(array(DB_FREFIX.'brand'),array('id,name')),'id','name');
        if(isset($allGoods)) {
            foreach($allGoods as $key=>$value) {
                if($value->brand == 0) {
                    $value->brand = '其他品牌';
                } else {
                    $value->brand = $allBrand[$value->brand];
                }
            }
        }
        return $allGoods;
    }

    public function findListGoods() {
        //定义动态产生的sql语句
        $priceSQL = '';
        $brandSQL = '';
        $attrSQL = '';
        if(!empty($_GET['price'])) {       //如果网址包含price参数并且不为0，说明进行价格筛选
            $price = explode(',',$_GET['price']);
            $left = $price[0];
            $right = $price[1];
            $priceSQL = " AND price_sale BETWEEN $left AND $right ";  //拼装价格筛选语句
        }
        if(!empty($_GET['brand'])) {
            $_GET['brand'] == 'other' ? 0 : $_GET['brand'];
            $brandSQL = " AND brand={$_GET['brand']} ";
        }
        if(!empty($_GET['attr'])) {
            $attr = explode(':',$_GET['attr']);
            $attrSQL = " AND attr LIKE '%$attr[0]%$attr[1]%'";
        }
        $allGoods = parent::select(array(DB_FREFIX.'goods g'),array('id','price_sale','price_market','nav','name','thumbnail','is_up','unit','(SELECT COUNT(*) FROM mall_commend c WHERE is_block=0 AND c.goodsid=g.id) AS count'),
                array('limit'=>$this->limit,
                        'order'=>'date DESC',
                        'where'=>array('nav in('.$this->getNavId().') AND is_up=1'.$priceSQL.$brandSQL.$attrSQL)));
        if(isset($allGoods)) {
            foreach($allGoods as $value) {
                $img = new Image($value->thumbnail);
                $img->thumbAsSameScale();
                //新增一个存放220x220图片地址的属性
                $value->thumbnail_small = $img->getThumbPath();
                //获得这个商品在本月的销售量
                $value->sales = 0;
                $record = parent::select(array(DB_FREFIX.'record'),array('num'),array('where'=>array("goodsid='$value->id' AND MONTH(NOW())-MONTH(date)<1")));
                if(isset($record)) {
                    foreach($record as $key2=>$value2) {
                        $value->sales += $value2->num;
                    }
                }
            }
        }

        return $allGoods;
    }

    public function findFrontAttr() {
        $allAttr = parent::select($this->tables,array('attr'),array('where'=>array('nav in ('.$this->getNavId().')')));
        $cAttr = array();
        if(isset($allAttr)) {
            foreach($allAttr as $value) {
                $t = explode(';',$value->attr);
                foreach($t as $k=>$v) {     //把属性名称作为key，属性具体值作为value
                    $tk = mb_substr($v,0,mb_strpos($v,':',0,'utf-8'),'utf-8');
                    $tv = explode('|',mb_substr($v,mb_strpos($v,':')+1));
                    $cAttr[$tk] = $tv;
                }

            }
        }
        return $cAttr;
    }

    public function findOne() {
        $condition = array('id='.$this->R['id']);
        return parent::select($this->tables,array('id','name','sn','attr','price_sale','price_market','price_cost','keyword','unit','weight','thumbnail','content','is_up','is_freight','inventory','warn_inventory','nav','brand','service'),array('where'=>$condition));
    }

    public function findDetailsGoods() {
        $oneGoods = parent::select($this->tables,array('id','attr','brand','name','sn','thumbnail','price_sale','price_market','inventory','unit','weight','is_freight','content','service','is_up','nav'),array('where'=>array('id='.$this->R['goodsid']),'limit'=>1));
        $allBarnd = Tool::setObjectArray(parent::select(array(DB_FREFIX.'brand'),array('id','name')),'id','name');
        if($oneGoods[0]->brand == 0) {
            $oneGoods[0]->brandName = '其他品牌';
        } else {
            $oneGoods[0]->brandName = $allBarnd[$oneGoods[0]->brand];
        }
        $oneGoods[0]->content = htmlspecialchars_decode($oneGoods[0]->content);
        //查找商品的售后服务
        $condition = array("id='{$oneGoods[0]->service}'");
        $service = parent::select(array(DB_FREFIX.'service'),array('content'),array('where'=>$condition));
        $oneGoods[0]->service = htmlspecialchars_decode($service[0]->content);
        $img = new Image($oneGoods[0]->thumbnail);
        $img->thumbAsSameScale();
        //新增一个存放220x220图片地址的属性
        $oneGoods[0]->thumbnail_small = $img->getThumbPath();

        //获得这个商品在本月的销售量
        $oneGoods[0]->sales = 0;
        $record = parent::select(array(DB_FREFIX.'record'),array('num'),array('where'=>array("goodsid='{$oneGoods[0]->id}' AND MONTH(NOW())-MONTH(date)<1")));
        if(isset($record)) {
            foreach($record as $key=>$value) {
                $oneGoods[0]->sales += $value->num;
            }
        }

        //获得这个商品总销售量
        $oneGoods[0]->total_sales = 0;
        $record = parent::select(array(DB_FREFIX.'record'),array('num'),array('where'=>array("goodsid='{$oneGoods[0]->id}'")));
        if(isset($record)) {
            foreach($record as $key=>$value) {
                $oneGoods[0]->total_sales += $value->num;
            }
        }

        //更新同一商品的浏览记录
        if(isset($_COOKIE['viewRecord'][$oneGoods[0]->id])) {
            setcookie('viewRecord['.$oneGoods[0]->id.']','',time()-1);      //清空原来的记录
        }

        //如果浏览记录超过5条，当增加到第六条的时候把最旧的一条记录清空
        if(isset($_COOKIE['viewRecord'])) {
            if(count($_COOKIE['viewRecord']) > 2) {
                $keys = array_keys($_COOKIE['viewRecord']);
                setcookie('viewRecord['.$keys[0].']','',time()-1);
            }
        }

        //增加浏览记录
        setcookie('viewRecord['.$oneGoods[0]->id.']',
                     serialize(
                             array(
                                 'id'=>$oneGoods[0]->id,
                                 'name'=>$oneGoods[0]->name,
                                 'thumbnail'=>$oneGoods[0]->thumbnail,
                                 'nav'=>$oneGoods[0]->nav,
                                 'price'=>$oneGoods[0]->price_sale,
                              )),
        time() + 60 * 60 * 24 * 7
        );
        return $oneGoods;
    }

    //获取当月热销的五件商品
    public function findHotGoods() {
        $allGoods = parent::select(array(DB_FREFIX.'goods'),array('id','name','thumbnail','price_sale','nav'),
                                   array('limit'=>'0,5',
                                          'where'=>array('nav in('.$this->getNavId().') AND is_up=1')));
        if(isset($allGoods)) {
            foreach($allGoods as $key=>$value) {
                //获得这个商品在本月的销售量
                $value->sales = 0;
                $record = parent::select(array(DB_FREFIX.'record'),array('num'),array('where'=>array("goodsid='$value->id' AND MONTH(NOW())-MONTH(date)<1")));
                if(isset($record)) {
                    foreach($record as $key2=>$value2) {
                        $value->sales += $value2->num;
                    }
                }
            }
            //冒泡排序,把当月销量越高的往越靠前排序
            foreach($allGoods as $key=>$value) {
                $next = $key + 1;
                foreach($allGoods as $k=>$v) {
                    if($next <= (count($allGoods)-1)) {
                        if($allGoods[$key]->sales < $allGoods[$next]->sales) {
                            $temp = $allGoods[$key];
                            $allGoods[$key] = $allGoods[$next];
                            $allGoods[$next] = $temp;
                        }
                    }
                    $next = $next + 1;
                }
            }
        }
        return $allGoods;

    }

    //获取浏览记录
    public function getViewRecord() {
        $viewRecord = array();
        if(isset($_COOKIE['viewRecord'])) {
            foreach($_COOKIE['viewRecord'] as $key=>$value) {
                $viewRecord[$key] = unserialize($value);
            }
        }
        return array_reverse($viewRecord);            //最近浏览的记录排在最前面
    }

    //情况浏览记录
    public function clearViewRecord() {
        if(isset($_COOKIE['viewRecord'])) {
            foreach($_COOKIE['viewRecord'] as $key=>$value) {
                setcookie('viewRecord['.$key.']','',time()-1);
            }
        }
        return true;
    }


    public function total() {
        if(!isset($_GET['id'])) {
            return parent::total();
        } else {
            return parent::total(array('where'=>array('nav in ('.$this->getNavId().')')));
        }
    }

    public function add() {
        $condition = array('sn='.$this->R['sn']);
        if(!$this->check->addCheck($this,$condition)) $this->check->displayError();
        $needData = $this->getRequest()->filter($this->fields);
        $needData['date'] = Tool::getDate();
        $needData['attr'] = $this->formatNav($needData);
        return parent::add($needData);
    }

    public function update() {
        $condition = array('sn='.$this->R['sn'],'id<>'.$this->R['id']);
        if(!$this->check->updateCheck($this,$condition)) $this->check->displayError();
        $condition = array('id='.$this->R['id']);
        $updateData = $this->getRequest()->filter($this->fields);
        $updateData['attr'] = $this->formatNav($updateData);;
        return parent::update($updateData,$condition);
    }

    public function delete() {
        $condition = array('id='.$this->R['id']);
        if(!$this->check->oneCheck($this,$condition)) $this->check->displayError();
        return parent::delete($condition);
    }

    //获取所有父类的子类id，如果没有子类则把父类id返回
    private function getNavId() {
        $idArr = parent::select(array(DB_FREFIX.'nav'),array('id'),array('where'=>array('sid='.$this->R['navid'])));
        $id = '';
        if(isset($idArr)) {
            foreach($idArr as $value) {
                $id .= $value->id.',';
            }
            $id = substr($id,0,-1);
        } else {
            $id = $_GET['navid'];
        }
        return $id;
    }

    public function formatNav($data) {
        $attr = '';
        if(isset($data['attr'])) {
            foreach($data['attr'] as $key=>$value) {
                $attr .= $key.':';
                foreach($value as $v) {
                    $attr .= $v.'|';
                }
                $attr = substr($attr,0,-1).';';
            }
            $attr = substr($attr,0,-1);
        }
        return $attr;
    }

    public function isUp() {
        if(!Validate::isNullString($this->R['id']) && !Validate::isNullString($_GET['act'])) {
            $condition = array('id='.$this->R['id']);
            if($_GET['act'] == 'up') {
                return parent::update(array('is_up'=>1),$condition);
            } else if($_GET['act'] == 'down') {
                return parent::update(array('is_up'=>0),$condition);
            }
        }
    }

    //判断商品是否超量
    public function isNoMore() {
        $goods = parent::select($this->tables,array('inventory'),array('where'=>array('id='.$this->R['aid'])));
        $inventory = $goods[0]->inventory;
        if($_POST['num'] > $inventory) {
            echo 1;
        }
    }

    //设置库存
    public function setInventory() {
        $goods = array();
        foreach($_COOKIE['cart'] as $key=>$value) {
            $temp = unserialize($value);
            $goods[$key] = $temp['num'];
        }
        foreach($goods as $key=>$value) {
            $condition = array("id='$key'");
            $updateData['inventory'] = array('inventory-'.$value);
            parent::update($updateData,$condition);
        }
    }

}
?>